string format 應該是大家常常用到的
但是 有很多好用的技巧 想給離開新手村的你知道
先上範例Code
void Main()
{
var prodcutList = new List<Prodcut>()
{
new Prodcut{ Name= "Sports & Outdoors", Price= 1200 },
new Prodcut{ Name= "Pet Supplies", Price= 2400 },
new Prodcut{ Name= "Toys & Games", Price= 5600 }
};
$"{nameof(Prodcut.Name)} {nameof(Prodcut.Price)}".Dump();
foreach (var prodcut in prodcutList)
{
$"{prodcut.Name} {prodcut.Price}".Dump();
}
}
public class Prodcut
{
public string Name { get; set; }
public int Price { get; set; }
}
結果是
預設靠右 (前面補空白)
加上負號靠左 (後面補空白)
$"{prodcut.Name,-20} {prodcut.Price,-20}".Dump();
var phone = 8660212344321;
$"{phone:+### (##) ####-####}".Dump();
+866 (02) 1234-4321
var id = 990;
$"{id:000000}".Dump();
$"{id:.00}".Dump();
000990
990.00
補文字$"{id.ToString().PadLeft(5, 'A')}".Dump();
AA990
var enUS = new CultureInfo("en-US");
$"{enUS.Name}: {dateValue.ToString(enUS)}".Dump();
en-US: 4/16/2021 10:40:00 AM
@"new line \r\n\t".Dump();
@"Using unicode: \u25a1".Dump();
new line \r\n\t
Using unicode: \u25a1
可以試看看不加@ 結果會怎樣
.net 比較大小有用大於0 小於0 等於 0 三種結果表示比較大小
對應 大於0;小於0;等於0
void Main()
{
var prodcutList = new List<Prodcut>()
{
new Prodcut{Rating=30},
new Prodcut{Rating=-20 },
new Prodcut{Rating=00 }
};
foreach (var prodcut in prodcutList)
{
$"{prodcut.Rating.ToString("Good ;Bad ;Not Rated")}".Dump();
}
foreach (var prodcut in prodcutList)
{
$"{prodcut.Rating.ToString("Good #;Bad -#;Not Rated")}".Dump();
}
}
public class Prodcut
{
public int Rating { get; set; }
}
Good
Bad
Not Rated
Good 30
Bad -20
Not Rated
關於時間相關的已經有人整理的非常棒了 請看
Day14-C#-輸出格式好幫手String.Format/有$好辦事=ˇ=
這六個技巧 如果你都已經知道了 那恭喜你 在新手村練得很紮實